package util

import (
	"base-web/global"
	f2 "base-web/util/f"
	"base-web/util/oss_upload"
	"fmt"
	"github.com/gin-gonic/gin"
	"os"
	"strings"
	"time"
)

type Upload struct {
	Url string `json:"url"`
}

//gin普通文件上传
func GinUpload(c *gin.Context, f string) (Upload, error) {
	var err error
	var upload Upload
	file, err := c.FormFile("file")
	if err != nil {
		return upload, err
	}
	s, _ := os.Getwd()
	year, month, day := time.Now().Date()
	dir := fmt.Sprintf("%s%s%d%d%d/", s, global.BASE_CONFIG.Upload.Path, year, month, day)
	//创建文件夹
	f2.CreateDir(dir)
	suffix := strings.Split(file.Filename, ".")[1]
	fileName := fmt.Sprintf("%d.%s", time.Now().Unix(), suffix)
	localFileName := fmt.Sprintf("%s%s", dir, fileName)
	err = c.SaveUploadedFile(file, localFileName)
	if err != nil {
		return upload, err
	}

	//如果开启oss上传就上传到oss，否则返回本地路径
	if global.BASE_CONFIG.Upload.UploadToOss {
		//上传到oss
		url, err := oss_upload.OssUpload(fileName, localFileName)
		upload.Url = url
		if err == nil {
			return upload, err
		}
		return upload, err
	} else {
		upload.Url = fmt.Sprintf("http://%s%s%d%d%d/%s", c.Request.Host, global.BASE_CONFIG.Upload.Path, year, month, day, fileName)
		return upload, err
	}
}
